<?php
/**
 * Created by PhpStorm.
 * User: hahastein
 * Date: 2018/5/22
 * Time: 1:08
 */

namespace Api\Controller;

use Think\Controller;
use \Yunpian\Sdk\YunpianClient;


class SmsController extends Controller {

    public function send(){
        header("Access-Control-Allow-Origin: *");
        $data_moblie = I('post.mobile',0);

        if($data_moblie == 0){
            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => '手机号不能为空'
            ),'JSON');
        }


        //生成随机验证码
        $randCheckNum = $this->randomKeys(6);

        $smsInsert = M('dm_user_msgcode')->add(array('mobile'=>$data_moblie, 'code' => $randCheckNum, 'addtime' => time()));

        if($smsInsert) {
                $apikey = "02ae7e44228fe425c29ad41c401523ab";
            $clnt = YunpianClient::create($apikey);
            $param = [YunpianClient::MOBILE => $data_moblie, YunpianClient::TEXT => '【雕玛APP】您的验证码是' . $randCheckNum];
            $r = $clnt->sms()->single_send($param);

            if ($r->isSucc()) {
                $returnData = $r->data();
                if($returnData['code'] == 0){
                    $this->ajaxReturn(array(
                        'code' => 200,
                        'msg' => '发送验证码成功'
                    ),'JSON');
                }
            }

            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => '发送验证码失败'
            ),'JSON');
        }else{
            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => '验证码失败'
            ),'JSON');
        }

        die;
    }

    private function randomKeys($length)
    {
        $key='';
        $pattern='1234567890';
        for($i=0;$i<$length;++$i)
        {
            $key .= $pattern{mt_rand(0,9)}; // 生成php随机数
        }
        return $key;
    }



}